package com.finalterm.order.service.impl;

import com.finalterm.common.constant.Constants;
import com.finalterm.common.result.Result;
import com.finalterm.order.feign.ProductServiceClient;
import com.finalterm.order.service.CompensationTaskService;
import com.finalterm.order.service.StockConfirmService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * 库存确认服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class StockConfirmServiceImpl implements StockConfirmService {

    private final ProductServiceClient productServiceClient;
    private final CompensationTaskService compensationTaskService;

    @Override
    @Async("stockConfirmExecutor")
    public void confirmStockDeductionAsync(String orderNo, Long productId, Integer quantity, String orderStatus) {
        log.info("开始异步确认库存扣减，订单号：{}，商品ID：{}，数量：{}，订单状态：{}", 
                orderNo, productId, quantity, orderStatus);
        
        try {
            boolean success = confirmStockDeduction(orderNo, productId, quantity, orderStatus);
            if (success) {
                log.info("异步库存确认成功，订单号：{}", orderNo);
            } else {
                log.warn("异步库存确认失败，订单号：{}，将创建补偿任务", orderNo);
                // 如果是已支付订单的库存确认失败，需要特殊处理
                if (Constants.ORDER_STATUS_PAID.equals(orderStatus)) {
                    // 对于已支付订单，库存确认失败可能意味着数据不一致
                    // 这里可以发送告警或者创建特殊的补偿任务
                    log.error("已支付订单库存确认失败，可能存在数据不一致，订单号：{}", orderNo);
                }
            }
        } catch (Exception e) {
            log.error("异步库存确认异常，订单号：{}，异常：{}", orderNo, e.getMessage(), e);
            // 异常情况下也可以考虑创建补偿任务
            if (Constants.ORDER_STATUS_PAID.equals(orderStatus)) {
                log.error("已支付订单库存确认异常，可能存在数据不一致，订单号：{}", orderNo);
            }
        }
    }

    @Override
    public boolean confirmStockDeduction(String orderNo, Long productId, Integer quantity, String orderStatus) {
        try {
            // 调用product-service确认库存扣减
            Result<Boolean> result = productServiceClient.confirmStockDeduction(orderNo, productId, quantity, orderStatus);
            
            if (result.getCode() == 200 && result.getData() != null && result.getData()) {
                log.info("库存确认成功，订单号：{}，商品ID：{}，数量：{}", orderNo, productId, quantity);
                return true;
            } else {
                log.warn("库存确认失败，订单号：{}，响应：{}", orderNo, result.getMessage());
                return false;
            }
        } catch (Exception e) {
            log.error("库存确认调用异常，订单号：{}，异常：{}", orderNo, e.getMessage(), e);
            return false;
        }
    }
}
